<template>
  <div>
    <el-upload
      class="upload-demo"
      :action='BASE_URL + "/attachment"'
      :on-preview="handlePreview"
      :with-credentials="true"
      :data="
        step
          ? {
              fid: listId,
              type: fileType,
              step: step,
            }
          : {
              fid: listId,
              type: fileType,
            }
      "
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleSuccess"
      :file-list="fileList"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>

export default {
  name: "cusUpload",
  props: {
    /*查询文件列表的id*/
    listId: {
      type: String,
      default: "",
    },
    /**文件类型 */
    fileType: {
      type: String,
      required: true,
    },
    /**step */
    step: {
      type: String,
      default: () => "",
    },
    fileList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_URL,
      //   fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  methods: {
    filterImg(list) {
      const _list = [];
      list?.forEach((item) => {
        // let v = {};
        _list.push(`${this.BASE_URL+item.url}`);
        // const reg = /(\.(png|jpeg|jpg)$)/;
        // if (item.extra) v = item.extra;
        // if (reg.test(v.path)) {
        //   _list.push(`${item.url}`);
        // }
      });
      return _list;
    },
    async handleRemove(file, fileList) {
      if (file.response) {
        const res = await this.$axios.delete(`/attachment?id=${file.response.id}`);
        if (!res.data.errors) {
          this.$message.success("删除成功");
        }
      } else {
        const res = await this.$axios.delete(`/attachment?id=${file.id}`)
        if (!res.data.errors) {
          this.$message.success("删除成功");
        }
      }
    },
    handleSuccess(response, file, fileList) {
      this.$emit("getFileList", fileList);
    },
    handlePreview(file) {

      this.dialogVisible = true;
      if (file.raw) {
        this.dialogImageUrl = URL.createObjectURL(file.raw);
      } else {
        this.dialogImageUrl = process.env.VUE_APP_BASE_URL + file.url;
      }
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>
